import time
import hmac
import hashlib
import requests
import json

# ==== 设备信息 ====
product_key = "cukkm7vdszccxdje"
device_key = "oLdIakAX23H2Eec"
device_secret = "CB528E2765DBC12F11D05E98E9F97FF0"
operator = "0"  # 非蜂窝网络填"0"，蜂窝请填"1"-"4"
device_id = "ABC123456789"  # SN码 / MAC地址 / ICCID（10~32位）

# ==== 时间戳 ====
timestamp = str(int(time.time() * 1000))  # 毫秒级时间戳

# ==== 签名方法 ====
sign_method = "hmacsha256"  # 仅参与签名字符串拼接 + 请求体参数

# ==== 拼接签名字符串 ====
sign_string = device_id + device_key + product_key + sign_method + operator + timestamp

# ==== 生成签名 ====
sign = hmac.new(
    key=device_secret.encode('utf-8'),
    msg=sign_string.encode('utf-8'),
    digestmod=hashlib.sha256
).hexdigest()

# ==== 构造请求体 ====
payload = {
    "productKey": product_key,
    "deviceKey": device_key,
    "operator": operator,
    "deviceId": device_id,
    "timestamp": timestamp,
    "signMethod": sign_method,  # 保留，用于请求体
    "sign": sign
}

print("请求体内容：")
print(json.dumps(payload, indent=2, ensure_ascii=False))
# ==== 请求 Token ====
url = "https://dmp-https.cuiot.cn:8943/auth"
headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, headers=headers, data=json.dumps(payload))

if response.status_code == 200:
    try:
        resp_json = response.json()
        if resp_json.get("code") == "000000":
            token = resp_json["data"]["token"]
            print("✅ 获取 token 成功:", token)
        else:
            print("❌ 接口返回错误:", resp_json.get("message"))
    except Exception as e:
        print("⚠️ 无法解析 JSON:", str(e))
else:
    print("❌ HTTP 请求失败，状态码:", response.status_code)
